package org.xiaoyu.rpc.remoting.transport.cllient;

import lombok.extern.slf4j.Slf4j;
import org.xiaoyu.rpc.common.constant.RpcError;
import org.xiaoyu.rpc.common.exception.RpcException;
import org.xiaoyu.rpc.remoting.packet.AppResponse;
import org.xiaoyu.rpc.remoting.packet.Invocation;
import org.xiaoyu.rpc.remoting.packet.PacketStatusConstant;

/**
 * Created By Have
 * 2021/7/5 17:52
 */
@Slf4j
public class RpcMessageChecker {

    public static final String INTERFACE_NAME = "interfaceName";

    private RpcMessageChecker() {
    }

    public static void check(Invocation invocation, AppResponse rpcResponse) {
        if (rpcResponse == null) {
            log.error("调用服务失败,serviceName:{}", invocation.getServiceName());
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE + ":" + INTERFACE_NAME + ":" + invocation.getServiceName());
        }

        if (!invocation.getRequestId().equals(rpcResponse.getRequestId())) {
            throw new RpcException(RpcError.RESPONSE_NOT_MATCH + ":" + INTERFACE_NAME + ":" + invocation.getServiceName());
        }
        if (rpcResponse.getStatusCode().equals(PacketStatusConstant.ERROR)) {
            log.error(rpcResponse.getErrorMessage());
            throw new RuntimeException("Request Error");
        }
        if (rpcResponse.getStatusCode().equals(PacketStatusConstant.TIMEOUT)) {
            log.error(rpcResponse.getErrorMessage());
            throw new RuntimeException("Response Timeout");
        }
        if (!rpcResponse.isSuccess()) {
            log.error("调用服务失败,serviceName:{},RpcResponse:{}", invocation.getServiceName(), rpcResponse.getException());
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE + ":" + INTERFACE_NAME + ":" + invocation.getServiceName());
        }


    }

}
